//
//  WechatSdkManager.m

//

#import "WechatSdkManager.h"
#import "NativeSdkHelper.h"


#import <sys/utsname.h>


#import "AVFoundation/AVFoundation.h"



#include "cocos/scripting/js-bindings/jswrapper/SeApi.h"




@implementation WechatSdkManager

static WechatSdkManager *_sharedInstance = nil;

//单例
+(instancetype)sharedInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[WechatSdkManager alloc] init];
    });
    return _sharedInstance;
}

//回调给研发，放主线程
-(void)CallbackToJSWithMethodName:(NSString*)name ret:(id )retObj {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSString* retStr = retObj;
        if ([[NativeSdkHelper sharedInstance] isEmptyString:retStr]) {
            //加个判断，防止空字符串闪退
            retStr = @"";
        }

        //转义替换
        NSMutableString *mutStr = [NSMutableString stringWithString:retStr];
        NSRange range = NSMakeRange(0, mutStr.length);
        [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range];
        range = NSMakeRange(0, mutStr.length);
        [mutStr replaceOccurrencesOfString:@"\\" withString:@"\\\\" options:NSLiteralSearch range:range];
        NSString* etc_result = [NSString stringWithFormat:@"%@", mutStr];

        //回调给cocos
          NSString* funcNameStr = [NSString stringWithFormat:@"WechatSdkManager.%@", name];
          std::string funcName = [funcNameStr UTF8String];
          std::string param = [etc_result UTF8String];
          std::string jsCallStr = funcName+"('"+param+"');";
          se::ScriptEngine::getInstance()->evalString(jsCallStr.c_str());
    });
}


//初始化
-(void)sdkInit:(NSString* )jsonStr {
    NSLog(@"WechatSdkManager.init=====");
//    if ([[NativeSdkHelper sharedInstance]isEmptyString:jsonStr]) {
//        //加个判断，防止空字符串闪退
//        jsonStr = @"";
//        return;
//    }
    
    //在register之前打开log, 后续可以根据log排查问题
    [WXApi startLogByLevel:WXLogLevelDetail logBlock:^(NSString *log) {
        NSLog(@"WeChatSDK: %@", log);
    }];
    
    //向微信注册
    NSLog(@"注册=====");
//    [WXApi registerApp:@"wx2b30957daca6d855" universalLink:@"https://your_domain/app/"];
    [WXApi registerApp:@"wxa16c47ab675b6edb" universalLink:@"https://renhuai"];
 
//    //调用自检函数
//    [WXApi checkUniversalLinkReady:^(WXULCheckStep step, WXCheckULStepResult* result) {
//        NSLog(@"检查微信=%@, %u, %@, %@", @(step), result.success, result.errorInfo, result.suggestion);
//    }];
    
}


+(void)login:(NSString* )jsonStr {
    NSLog(@"WechatSdkManager==login===%@", jsonStr);
    //构造SendAuthReq结构体
    if (WXApi.isWXAppInstalled){
        SendAuthReq* req =[[[SendAuthReq alloc]init]autorelease];
        req.scope = @"snsapi_userinfo";
        req.state = jsonStr;
        //第三方向微信终端发送一个SendAuthReq消息结构
        [WXApi sendReq:req completion:nil];
    }else{
        SendAuthReq* req =[[[SendAuthReq alloc]init]autorelease];
        req.scope = @"snsapi_userinfo";
        req.state = jsonStr;
        //第三方向微信终端发送一个SendAuthReq消息结构
        [WXApi sendAuthReq:req viewController:[[NativeSdkHelper sharedInstance] getViewController] delegate:nil completion:nil];
    }
}


+(void)share_url:(NSString* )jsonStr {
    NSLog(@"WechatSdkManager==share_url===%@", jsonStr);
    NSDictionary* dic = [[NativeSdkHelper sharedInstance] transferToDictionaryWithJsonString:jsonStr];
    if (dic == nil || ![dic isKindOfClass:[NSDictionary class]]) {
       NSLog(@"%s：dic is null", __FUNCTION__);
       return;
    }
    NSString* title =[dic objectForKey:@"title"];
    NSString* description =[dic objectForKey:@"description"];
    NSString* url  =[dic objectForKey:@"url"];
    int scene =[[dic objectForKey:@"scene"] intValue];
    

    WXWebpageObject *webpageObject = [WXWebpageObject object];
    webpageObject.webpageUrl = url;
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = title;
    message.description =description;
    message.mediaObject = webpageObject;
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = scene;
    [WXApi sendReq:req completion:nil];
    
    NSLog(@"WechatSdkManager==share_url=end");
    
}

+(void)share_img:(NSString* )jsonStr {
    NSLog(@"WechatSdkManager==share_img===%@", jsonStr);
    NSDictionary* dic = [[NativeSdkHelper sharedInstance] transferToDictionaryWithJsonString:jsonStr];
    if (dic == nil || ![dic isKindOfClass:[NSDictionary class]]) {
       NSLog(@"%s：dic is null", __FUNCTION__);
       return;
    }
    NSString* picPath =[dic objectForKey:@"picPath"];
    int scene =[[dic objectForKey:@"scene"] intValue];
    
    NSData *imageData = [NSData dataWithContentsOfFile:picPath];
    
    WXImageObject *imageObject = [WXImageObject object];
    imageObject.imageData = imageData;
    WXMediaMessage *message = [WXMediaMessage message];
    NSString *thumbFile = [[NSBundle mainBundle] pathForResource:picPath ofType:@"jpg"];
    message.thumbData = [NSData dataWithContentsOfFile:thumbFile];
    message.mediaObject = imageObject;
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = scene;
    [WXApi sendReq:req completion:nil];
}



@end
